/* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
   Copyright (C) 2017 Red Hat, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <common/generated_server_marshallers.h>
#include <spice/stream-device.h>

#include "red-channel-client.h"
#include "gpunvidia-channel.h"
#include "reds.h"
#include "common-graphics-channel.h"
#include "display-limits.h"
#include "gpunvidia.h" 


#define TYPE_GPUNVIDIA_CHANNEL_CLIENT gpunvidia_channel_client_get_type()

#define GPUNVIDIA_CHANNEL_CLIENT(obj) \
    (G_TYPE_CHECK_INSTANCE_CAST((obj), TYPE_GPUNVIDIA_CHANNEL_CLIENT, GpuNvidiaChannelClient))
#define GPUNVIDIA_CHANNEL_CLIENT_CLASS(klass) \
    (G_TYPE_CHECK_CLASS_CAST((klass), TYPE_GPUNVIDIA_CHANNEL_CLIENT, GpuNvidiaChannelClientClass))
#define IS_GPUNVIDIA_CHANNEL_CLIENT(obj) \
    (G_TYPE_CHECK_INSTANCE_TYPE((obj), TYPE_GPUNVIDIA_CHANNEL_CLIENT))
#define IS_GPUNVIDIA_CHANNEL_CLIENT_CLASS(klass) \
    (G_TYPE_CHECK_CLASS_TYPE((klass), TYPE_GPUNVIDIA_CHANNEL_CLIENT))
#define GPUNVIDIA_CHANNEL_CLIENT_GET_CLASS(obj) \
    (G_TYPE_INSTANCE_GET_CLASS((obj), TYPE_GPUNVIDIA_CHANNEL_CLIENT, GpuNvidiaChannelClientClass))

typedef struct GpuNvidiaChannelClient GpuNvidiaChannelClient;
typedef struct GpuNvidiaChannelClientClass GpuNvidiaChannelClientClass;

/* we need to inherit from CommonGraphicsChannelClient
 * to get buffer handling */
struct GpuNvidiaChannelClient {
    CommonGraphicsChannelClient parent;

    /* current video stream id, <0 if not initialized or
     * we are not sending a stream */
    int stream_id;
};

struct GpuNvidiaChannelClientClass {
    CommonGraphicsChannelClientClass parent_class;
};

GType gpunvidia_channel_client_get_type(void) G_GNUC_CONST;

G_DEFINE_TYPE(GpuNvidiaChannelClient, gpunvidia_channel_client, TYPE_COMMON_GRAPHICS_CHANNEL_CLIENT)

struct GpuNvidiaChannel
{
    RedChannel parent;

    RedCharDevice *chardev; /* weak */
    SpiceCharDeviceInstance *chardev_sin;
    RedCharDeviceWriteBuffer *recv_from_client_buf;
    uint8_t port_opened;

    /* current video stream id, <0 if not initialized or
     * we are not sending a stream */
    int stream_id;
    /* size of the current video stream */
    unsigned width, height;

    /* callback to notify when a stream should be started or stopped */
    gpunvidia_channel_start_proc start_cb;
    void *start_opaque;

    /* monitor id */
    int monitor_id;
};

struct GpuNvidiaChannelClass {
    RedChannelClass parent_class;
};

G_DEFINE_TYPE(GpuNvidiaChannel, gpunvidia_channel, RED_TYPE_CHANNEL)

enum {
    RED_PIPE_ITEM_TYPE_SURFACE_CREATE = RED_PIPE_ITEM_TYPE_COMMON_LAST,
    RED_PIPE_ITEM_TYPE_SURFACE_DESTROY,
    RED_PIPE_ITEM_TYPE_FILL_SURFACE,
    RED_PIPE_ITEM_TYPE_STREAM_CREATE,
    RED_PIPE_ITEM_TYPE_STREAM_DATA,
    RED_PIPE_ITEM_TYPE_STREAM_DESTROY,
    RED_PIPE_ITEM_TYPE_STREAM_ACTIVATE_REPORT,
    RED_PIPE_ITEM_TYPE_MONITORS_CONFIG,
};

typedef struct GpuNvidiaStreamCreateItem {
    RedPipeItem base;
    SpiceMsgDisplayStreamCreate stream_create;
} GpuNvidiaStreamCreateItem;

typedef struct GpuNvidiaStreamDataItem {
    RedPipeItem base;
    GpuNvidiaChannel *channel;
    // NOTE: this must be the last field in the structure
    SpiceMsgDisplayStreamData data;
} GpuNvidiaStreamDataItem;

#define PRIMARY_SURFACE_ID 0

static gboolean g_device_is_dispose = TRUE;

void gpunvidia_device_set_dispose(gboolean val)
{
    g_device_is_dispose = val;
}

gboolean gpunvidia_device_is_dispose()
{
    return g_device_is_dispose;
}

static void gpunvidia_channel_client_on_disconnect(RedChannelClient *rcc);

static void
gpunvidia_channel_client_finalize(GObject *object)
{
    G_OBJECT_CLASS(gpunvidia_channel_client_parent_class)->finalize(object);
}

static void
gpunvidia_channel_client_class_init(GpuNvidiaChannelClientClass *klass)
{
    GObjectClass *object_class = G_OBJECT_CLASS(klass);
    RedChannelClientClass *channel_class = RED_CHANNEL_CLIENT_CLASS(klass);

    channel_class->on_disconnect = gpunvidia_channel_client_on_disconnect;
    object_class->finalize = gpunvidia_channel_client_finalize;
}

static void
gpunvidia_channel_client_init(GpuNvidiaChannelClient *client)
{
    client->stream_id = -1;
}

static void
gpunvidia_request_new_stream(GpuNvidiaChannel *, int);

static void
gpunvidia_mon_ext_clean_channels(void)
{
    for(int i=0; i<GPU_MAX_MONITORS; i++){
        g_gpu_ext->g_mon_ext[i]->m_gpunvidia_channel = NULL;
    }
}

static void
gpunvidia_channel_destroy()
{
    for(int i=0; i<GPU_MAX_MONITORS; i++){
        if(g_gpu_ext->g_mon_ext[i]->m_gpunvidia_channel){
            red_channel_destroy(RED_CHANNEL(g_gpu_ext->g_mon_ext[i]->m_gpunvidia_channel));
            g_gpu_ext->g_mon_ext[i]->m_gpunvidia_channel = NULL;
        }
        if(g_gpu_ext->g_mon_ext[i]->m_gpunvidia_cursor_channel){
            red_channel_destroy(RED_CHANNEL(g_gpu_ext->g_mon_ext[i]->m_gpunvidia_cursor_channel));
            g_gpu_ext->g_mon_ext[i]->m_gpunvidia_cursor_channel = NULL;
        }
    }
}

static void
gpunvidia_channel_client_on_disconnect(RedChannelClient *rcc)
{
    if(gpunvidia_device_is_dispose()){
        spice_warning("### %s:%d, destroy channel", __FUNCTION__, __LINE__);
        gpunvidia_channel_destroy();
        return ;
    }

    gpunvidia_mon_ext_clean_channels();

    RedChannel *red_channel = red_channel_client_get_channel(rcc);
    gpunvidia_request_new_stream(GPUNVIDIA_CHANNEL(red_channel), 0);
    if (red_channel_is_connected(red_channel)) {
        return;
    }

    GpuNvidiaChannel *channel = GPUNVIDIA_CHANNEL(red_channel);
    channel->stream_id = -1;
    channel->width = 0;
    channel->height = 0;
}

static GpuNvidiaChannelClient*
gpunvidia_channel_client_new(GpuNvidiaChannel *channel, RedClient *client, RedsStream *stream,
                          int mig_target, RedChannelCapabilities *caps)
{
    GpuNvidiaChannelClient *rcc;

    rcc = g_initable_new(TYPE_GPUNVIDIA_CHANNEL_CLIENT,
                         NULL, NULL,
                         "channel", channel,
                         "client", client,
                         "stream", stream,
                         "monitor-latency", FALSE,
                         "caps", caps,
                         NULL);

    return rcc;
}

static void
gpunvidia_marshall_monitors_config(RedChannelClient *rcc, GpuNvidiaChannel *channel, SpiceMarshaller *m)
{
    struct {
        SpiceMsgDisplayMonitorsConfig config;
        SpiceHead head;
    } msg = {
        { 1, 1, },
        {
            // monitor ID. These IDs are allocated per channel starting from 0
            0,
            PRIMARY_SURFACE_ID + 12 + channel->monitor_id,
            channel->width, channel->height,
            0, 0,
            0 // flags
        }
    };

    red_channel_client_init_send_data(rcc, SPICE_MSG_DISPLAY_MONITORS_CONFIG);
    spice_marshall_msg_display_monitors_config(m, &msg.config);
}

static void
gpunvidia_fill_base(SpiceMarshaller *m, const GpuNvidiaChannel *channel)
{
    SpiceMsgDisplayBase base;

    base.surface_id = PRIMARY_SURFACE_ID;
    base.box = (SpiceRect) { 0, 0, channel->width, channel->height };
    base.clip = (SpiceClip) { SPICE_CLIP_TYPE_NONE, NULL };

    spice_marshall_DisplayBase(m, &base);
}

static void
gpunvidia_channel_send_item(RedChannelClient *rcc, RedPipeItem *pipe_item)
{
    SpiceMarshaller *m = red_channel_client_get_marshaller(rcc);
    GpuNvidiaChannelClient *client = GPUNVIDIA_CHANNEL_CLIENT(rcc);
    GpuNvidiaChannel *channel = GPUNVIDIA_CHANNEL(red_channel_client_get_channel(rcc));

    switch (pipe_item->type) {
    case RED_PIPE_ITEM_TYPE_SURFACE_CREATE: {
        //spice_warning("### %s:%d type:%d", __FUNCTION__, __LINE__, pipe_item->type);
        red_channel_client_init_send_data(rcc, SPICE_MSG_DISPLAY_SURFACE_CREATE);
        SpiceMsgSurfaceCreate surface_create = {
            PRIMARY_SURFACE_ID,
            channel->width, channel->height,
            SPICE_SURFACE_FMT_32_xRGB, SPICE_SURFACE_FLAGS_PRIMARY | SPICE_SURFACE_FLAGS_STREAMING_MODE
        };
        spice_marshall_msg_display_surface_create(m, &surface_create);
        break;
    }
    case RED_PIPE_ITEM_TYPE_MONITORS_CONFIG:
        if (!red_channel_client_test_remote_cap(rcc, SPICE_DISPLAY_CAP_MONITORS_CONFIG)) {;
            return;
        }
        gpunvidia_marshall_monitors_config(rcc, channel, m);
        break;
    case RED_PIPE_ITEM_TYPE_SURFACE_DESTROY: {
        //spice_warning("### %s:%d type:%d", __FUNCTION__, __LINE__, pipe_item->type);
        red_channel_client_init_send_data(rcc, SPICE_MSG_DISPLAY_SURFACE_DESTROY);
        SpiceMsgSurfaceDestroy surface_destroy = { PRIMARY_SURFACE_ID };
        spice_marshall_msg_display_surface_destroy(m, &surface_destroy);
        break;
    }
    case RED_PIPE_ITEM_TYPE_FILL_SURFACE: {
        //spice_warning("### %s:%d type:%d", __FUNCTION__, __LINE__, pipe_item->type);
        red_channel_client_init_send_data(rcc, SPICE_MSG_DISPLAY_DRAW_FILL);

        gpunvidia_fill_base(m, channel);

        SpiceFill fill;
        fill.brush = (SpiceBrush) { SPICE_BRUSH_TYPE_SOLID, { .color = 0 } };
        fill.rop_descriptor = SPICE_ROPD_OP_PUT;
        fill.mask = (SpiceQMask) { 0, { 0, 0 }, NULL };
        SpiceMarshaller *brush_pat_out, *mask_bitmap_out;
        spice_marshall_Fill(m, &fill, &brush_pat_out, &mask_bitmap_out);
        break;
    }
    case RED_PIPE_ITEM_TYPE_STREAM_CREATE: {
        //spice_warning("### %s:%d type:%d", __FUNCTION__, __LINE__, pipe_item->type);
        GpuNvidiaStreamCreateItem *item = SPICE_UPCAST(GpuNvidiaStreamCreateItem, pipe_item);
        client->stream_id = item->stream_create.id;
        red_channel_client_init_send_data(rcc, SPICE_MSG_DISPLAY_STREAM_CREATE);
        spice_marshall_msg_display_stream_create(m, &item->stream_create);
        break;
    }
    case RED_PIPE_ITEM_TYPE_STREAM_ACTIVATE_REPORT: {
        //spice_warning("### %s:%d type:%d", __FUNCTION__, __LINE__, pipe_item->type);
        #if 0
        if (client->stream_id < 0
            || !red_channel_client_test_remote_cap(rcc, SPICE_DISPLAY_CAP_STREAM_REPORT)) {
            return;
        }
        SpiceMsgDisplayStreamActivateReport msg;
        msg.stream_id = client->stream_id;
        msg.unique_id = 1; // TODO useful ?
        msg.max_window_size = RED_STREAM_CLIENT_REPORT_WINDOW;
        msg.timeout_ms = RED_STREAM_CLIENT_REPORT_TIMEOUT;
        red_channel_client_init_send_data(rcc, SPICE_MSG_DISPLAY_STREAM_ACTIVATE_REPORT);
        spice_marshall_msg_display_stream_activate_report(m, &msg);
        #endif
        break;
    }
    case RED_PIPE_ITEM_TYPE_STREAM_DATA: {
        //spice_warning("### %s:%d type:%d", __FUNCTION__, __LINE__, pipe_item->type);
        GpuNvidiaStreamDataItem *item = SPICE_UPCAST(GpuNvidiaStreamDataItem, pipe_item);
        red_channel_client_init_send_data(rcc, SPICE_MSG_DISPLAY_STREAM_DATA);
        spice_marshall_msg_display_stream_data(m, &item->data);
        red_pipe_item_ref(pipe_item);
        spice_marshaller_add_by_ref_full(m, item->data.data, item->data.data_size,
                                         marshaller_unref_pipe_item, pipe_item);
        break;
    }
    case RED_PIPE_ITEM_TYPE_STREAM_DESTROY: {
        //spice_warning("### %s:%d type:%d", __FUNCTION__, __LINE__, pipe_item->type);
        if (client->stream_id < 0) {
            return;
        }
        SpiceMsgDisplayStreamDestroy stream_destroy = { client->stream_id };
        red_channel_client_init_send_data(rcc, SPICE_MSG_DISPLAY_STREAM_DESTROY);
        spice_marshall_msg_display_stream_destroy(m, &stream_destroy);
        client->stream_id = -1;
        break;
    }
    default:
        spice_error("invalid pipe item type");
    }

    red_channel_client_begin_send_message(rcc);
}

static bool
gpunvidia_handle_message(RedChannelClient *rcc, uint16_t type, uint32_t size, void *msg)
{
    switch (type) {
    case SPICE_MSGC_DISPLAY_INIT:
    case SPICE_MSGC_DISPLAY_PREFERRED_COMPRESSION:
        return true;
    case SPICE_MSGC_DISPLAY_STREAM_REPORT:
        /* TODO these will help tune the streaming reducing/increasing quality */
        return true;
    case SPICE_MSGC_DISPLAY_GL_DRAW_DONE:
        /* client should not send this message */
        return false;
    default:
        return red_channel_client_handle_message(rcc, type, size, msg);
    }
}

GpuNvidiaChannel*
gpunvidia_channel_new(RedsState *server, uint32_t id)
{
    return g_object_new(TYPE_GPUNVIDIA_CHANNEL,
                        "spice-server", server,
                        "core-interface", reds_get_core_interface(server),
                        "channel-type", SPICE_CHANNEL_DISPLAY,
                        // TODO this id should be after all qxl devices
                        "id", id,
                        "migration-flags", 0,
                        "handle-acks", TRUE, // TODO sure ??
                        NULL);
}

static void
gpunvidia_channel_connect(RedChannel *red_channel, RedClient *red_client, RedsStream *stream,
                       int migration, RedChannelCapabilities *caps)
{
    spice_printerr("### %s:%d red_channel:%p, red_client:%p, RedsStream:%p",
        __FUNCTION__, __LINE__, red_channel, red_client, stream);

    GpuNvidiaChannel *channel = GPUNVIDIA_CHANNEL(red_channel);
    GpuNvidiaChannelClient *client;

    spice_return_if_fail(stream != NULL);

    client = gpunvidia_channel_client_new(channel, red_client, stream, migration, caps);
    spice_return_if_fail(client != NULL);

    gpunvidia_request_new_stream(channel, 1);

    // TODO set capabilities like  SPICE_DISPLAY_CAP_MONITORS_CONFIG
    // see guest_set_client_capabilities
    RedChannelClient *rcc = RED_CHANNEL_CLIENT(client);
    red_channel_client_push_set_ack(rcc);

    // TODO what should happen on migration, dcc return if on migration wait ??
    red_channel_client_ack_zero_messages_window(rcc);

    spice_warning("monitor config: %dx%d", channel->width, channel->height);
    red_channel_pipes_add_type(red_channel, RED_PIPE_ITEM_TYPE_MONITORS_CONFIG);

    // "emulate" dcc_start
    red_channel_client_pipe_add_empty_msg(rcc, SPICE_MSG_DISPLAY_INVAL_ALL_PALETTES);

    // only if "surface"
    if (channel->width == 0 || channel->height == 0) {
        return;
    }
    return ;

    // pass proper data
    red_channel_client_pipe_add_type(rcc, RED_PIPE_ITEM_TYPE_SURFACE_CREATE);
    // surface data
    red_channel_client_pipe_add_type(rcc, RED_PIPE_ITEM_TYPE_FILL_SURFACE);
    // TODO monitor configs ??
    red_channel_client_pipe_add_empty_msg(rcc, SPICE_MSG_DISPLAY_MARK);
}

static void
gpunvidia_channel_constructed(GObject *object)
{
    ClientCbs client_cbs = { NULL, };
    RedChannel *red_channel = RED_CHANNEL(object);
    RedsState *reds = red_channel_get_server(red_channel);

    G_OBJECT_CLASS(gpunvidia_channel_parent_class)->constructed(object);

    client_cbs.connect = gpunvidia_channel_connect;
    red_channel_register_client_cbs(red_channel, &client_cbs, NULL);

    // TODO, send monitor to support multiple monitors in the future
    red_channel_set_cap(red_channel, SPICE_DISPLAY_CAP_MONITORS_CONFIG);
    red_channel_set_cap(red_channel, SPICE_DISPLAY_CAP_STREAM_REPORT);

    reds_register_channel(reds, red_channel);
}

static void
gpunvidia_request_new_stream(GpuNvidiaChannel *channel, int start)
{
    if (channel->start_cb) {
        spice_printerr("### %s:%d ", __FUNCTION__, __LINE__);
        channel->start_cb(channel->start_opaque, start, channel);
    }
}

static void
gpunvidia_channel_init(GpuNvidiaChannel *channel)
{
    channel->stream_id = -1;
    channel->width = 0;
    channel->height = 0;
}

static void
gpunvidia_channel_class_init(GpuNvidiaChannelClass *klass)
{
    GObjectClass *object_class = G_OBJECT_CLASS(klass);
    RedChannelClass *channel_class = RED_CHANNEL_CLASS(klass);

    object_class->constructed = gpunvidia_channel_constructed;

    channel_class->parser = spice_get_client_channel_parser(SPICE_CHANNEL_DISPLAY, NULL);
    channel_class->handle_message = gpunvidia_handle_message;

    channel_class->send_item = gpunvidia_channel_send_item;
}

void
gpunvidia_channel_change_format(GpuNvidiaChannel *channel, const StreamMsgFormat *fmt)
{
    RedChannel *red_channel = RED_CHANNEL(channel);

    spice_printerr("### %s:%d %dx%d, codec:%d", __FUNCTION__, __LINE__, fmt->width, fmt->height, fmt->codec);

    // send destroy old stream
    red_channel_pipes_add_type(red_channel, RED_PIPE_ITEM_TYPE_STREAM_DESTROY);

    // send new create surface if required
    if (channel->width != fmt->width || channel->height != fmt->height) {
        if (channel->width != 0 && channel->height != 0) {
            red_channel_pipes_add_type(red_channel, RED_PIPE_ITEM_TYPE_SURFACE_DESTROY);
        }
        channel->width = fmt->width;
        channel->height = fmt->height;
        red_channel_pipes_add_type(red_channel, RED_PIPE_ITEM_TYPE_SURFACE_CREATE);
        // TODO monitors config ??
        red_channel_pipes_add_type(red_channel, RED_PIPE_ITEM_TYPE_MONITORS_CONFIG);
        red_channel_pipes_add_empty_msg(red_channel, SPICE_MSG_DISPLAY_MARK);
    }

    // allocate a new stream id
    channel->stream_id = (channel->stream_id + 1) % NUM_STREAMS;

    // send create stream
    GpuNvidiaStreamCreateItem *item = g_new0(GpuNvidiaStreamCreateItem, 1);
    red_pipe_item_init(&item->base, RED_PIPE_ITEM_TYPE_STREAM_CREATE);
    item->stream_create.id = channel->stream_id;
    item->stream_create.flags = SPICE_STREAM_FLAGS_TOP_DOWN;
    item->stream_create.codec_type = fmt->codec;
    item->stream_create.stream_width = fmt->width;
    item->stream_create.stream_height = fmt->height;
    item->stream_create.src_width = fmt->width;
    item->stream_create.src_height = fmt->height;
    item->stream_create.dest = (SpiceRect) { 0, 0, fmt->width, fmt->height };
    item->stream_create.clip = (SpiceClip) { SPICE_CLIP_TYPE_NONE, NULL };
    red_channel_pipes_add(red_channel, &item->base);

    // activate stream report if possible
    //red_channel_pipes_add_type(red_channel, RED_PIPE_ITEM_TYPE_STREAM_ACTIVATE_REPORT);
}

static void
gpunvidia_data_item_free(RedPipeItem *base)
{
    GpuNvidiaStreamDataItem *pipe_item = SPICE_UPCAST(GpuNvidiaStreamDataItem, base);
    g_free(pipe_item);
}

void
gpunvidia_channel_send_data(GpuNvidiaChannel *channel, const void *data, size_t size, uint32_t mm_time)
{
    if (channel->stream_id < 0) {
        return;
    }

    RedChannel *red_channel = RED_CHANNEL(channel);

    GpuNvidiaStreamDataItem *item = g_malloc(sizeof(*item) + size);
    red_pipe_item_init_full(&item->base, RED_PIPE_ITEM_TYPE_STREAM_DATA,
                            gpunvidia_data_item_free);
    item->data.base.id = channel->stream_id;
    item->data.base.multi_media_time = mm_time;
    item->data.data_size = size;
    item->channel = channel;
    memcpy(item->data.data, data, size);
    red_channel_pipes_add(red_channel, &item->base);
}

void
gpunvidia_channel_register_start_cb(GpuNvidiaChannel *channel,
                                 gpunvidia_channel_start_proc cb, void *opaque)
{
    channel->start_cb = cb;
    channel->start_opaque = opaque;
}

void
gpunvidia_channel_reset(GpuNvidiaChannel *channel)
{
    RedChannel *red_channel = RED_CHANNEL(channel);

    // send destroy old stream
    red_channel_pipes_add_type(red_channel, RED_PIPE_ITEM_TYPE_STREAM_DESTROY);

    // destroy display surface
    if (channel->width != 0 && channel->height != 0) {
        red_channel_pipes_add_type(red_channel, RED_PIPE_ITEM_TYPE_SURFACE_DESTROY);
    }

    channel->stream_id = -1;
    channel->width = 0;
    channel->height = 0;

    if (!red_channel_is_connected(red_channel)) {
        return;
    }
}

void
gpunvidia_channel_set_monitor_id(GpuNvidiaChannel *channel, int monitor_id)
{
    channel->monitor_id = monitor_id;
}

int
gpunvidia_channel_get_monitor_id(const GpuNvidiaChannel *channel)
{
    return channel->monitor_id;
}


